<?php

namespace App\Http\Controllers\Counter;

use App\Enums\AssistantStatus;
use App\Enums\OrderItemType;
use App\Enums\TableStatus;
use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\Counter\AssistantChangeTableRequest;
use App\Http\Requests\Counter\ItemChangeAssistantRequest;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Table;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AssistantModifyController extends Controller
{
    public function changeTable(AssistantChangeTableRequest $request)
    {
        /**
         * @var OrderItem $orderItem
         * @var Table $toTable
         */
        $orderItem = OrderItem::find($request->order_item_id);
        $toTable = Table::find($request->to_table_id);

        if ($orderItem->type != OrderItemType::Assistant)
            return ApiResponseHelper::json([], 400, '订单项不是助教');

        if ($toTable->status != TableStatus::Used)
            return ApiResponseHelper::json([], 400, '目标桌台未开台');

        DB::transaction(function () use ($orderItem, $toTable) {

            /**
             * @var Order $toTableOrder
             * @var Order $currentOrder
             */
            $toTableOrder = $toTable->tableOrder;
            $currentOrder = $orderItem->order;

            $orderItem->order_id = $toTableOrder->id;
            $orderItem->save();

            $toTableOrder->sumMoney();
            $toTableOrder->save();

            $currentOrder->sumMoney();
            $currentOrder->save();
        });

        return ApiResponseHelper::json([]);
    }

    public function changeAssistant(ItemChangeAssistantRequest $request)
    {
        /**
         * @var User $assistant
         * @var OrderItem $orderItem
         */
        $assistant = User::find($request->to_assistant_user_id);
        $orderItem = OrderItem::find($request->order_item_id);

        if ($assistant->assistant_status != AssistantStatus::NotOnDuty)
            return ApiResponseHelper::json([], 400, '助教状态错误，可能繁忙或休息。');

        if ($orderItem->type != OrderItemType::Assistant)
            return ApiResponseHelper::json([], 400, '订单项不是助教');

        $orderItem->assistant_user_id = $assistant->id;
        $orderItem->save();

        return ApiResponseHelper::json([]);
    }
}
